package com.kitty.game.equip.handler;

import com.kitty.game.role.model.Role;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.model.RoleEquipField;
import com.kitty.game.attribute.config.Attribute;
import com.kitty.game.config.Equip;
import com.kitty.game.equip.EquipDataPool;
import com.kitty.game.equip.message.RespTransformJewelryComplete;
import com.kitty.mina.message.MessagePusher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.kitty.game.utils.Const.*;
import com.kitty.game.equip.handler.UpgradeHandler;

//Todo 0次60 1次90 2次150 3次240 4次360 5次510 6次710 7次960 8次1296 9次1610
@Component("TransformJewelryHandler")
@Slf4j
public class TransformJewelryHandler extends UpgradeHandler {
    private static final List<Integer> COST_ESSENCE = Arrays.asList(60, 90, 150, 240, 360, 510, 710, 960, 1296, 1610);
    private static final String ERROR_RESOURCES = "请放入正确的装备或材料。";
    private static final String MAX_TRANSFORM = "#R{0}#n转换次数已达上限。";
    private static final String TRANSFORM_TIME = "很抱歉，#R{0}#n属性转换冷却时间未到。";
    private static final String STONE = "超级女娲石";
    private static final String FAIL_MESSAGE = "很抱歉，没有找到需要转换的属性。";
    private static final String SUCCESS_MESSAGE = "你花费了#R2#n块超级女娲石和#R60#n点首饰精华，成功对#R{0}#n进行了一次属性转换。";

    @Override
    public String doUpgrade(Role role, Object... params) {
        RoleEquip roleEquip = (RoleEquip) params[0];
        Attribute attribute = (Attribute) params[1];
        String opType = (String) params[2];
        Equip equip = (Equip) params[3];

        RoleEquipField blueFields = roleEquip.getFields().get((short) 514);
        RoleEquipField bluePosFields = roleEquip.getFields().get((short) 5378);

        RoleEquipField pinkFields = roleEquip.getFields().get((short) 770);
        RoleEquipField pinkPosFields = roleEquip.getFields().get((short) 5634);

        /**扣除精华在前面扣除 否则后面转换的次数增加了*/
        int costEssence = getEssence(roleEquip.queryTransformCount());
        roleService.subtractJewelryEssence(role, costEssence);

        short fieldPos;
        if (opType.equals("prop")) {
            blueFields.getField().remove(attribute.getAttrId());
            fieldPos = attrService.getValue(bluePosFields.getField().get(attribute.getAttrId()).getValue()).shortValue();
            bluePosFields.getField().remove(attribute.getAttrId());
        } else {
            pinkFields.getField().remove(attribute.getAttrId());
            fieldPos = attrService.getValue(pinkPosFields.getField().get(attribute.getAttrId()).getValue()).shortValue();
            pinkPosFields.getField().remove(attribute.getAttrId());
        }
        roleEquip.addLimitTime(1);
//        roleEquip.addTransformCount(1);
//        roleEquip.addTransformTime(Math.toIntExact(System.currentTimeMillis() / 1000 + 60 * 60 * 24 * 7));

        equipService.transformField(equip, roleEquip.getFields(), fieldPos);
        refreshRoleEquip(role, roleEquip);
        RespTransformJewelryComplete transformJewelryComplete = new RespTransformJewelryComplete();
        transformJewelryComplete.setType(roleEquip.getPosition());
        MessagePusher.pushMessage(role, transformJewelryComplete);
        pushOperateResult(role, UPGRADE_SUCCESS);
        return MessageFormat.format(SUCCESS_MESSAGE, roleEquip.getName());
    }

    @Override
    public String acceptUpgrade(Role role, int upgradePos, String param) {
        RoleEquip roleEquip = equipService.getRoleEquipByPos(role, upgradePos);

        String[] strings = param.split("/");
        if (strings.length < 2) {
            return ERROR_OPTYPE;
        }
        String opType = strings[0];
        String attrName = strings[1];
        if (!opType.equals("prop2") && !opType.equals("prop")) {
            return ERROR_OPTYPE;
        }
        if (roleEquip == null || !isRightPosition(roleEquip.queryEquipPos(false)) || roleEquip.queryLevel() < 110) {
            return ERROR_RESOURCES;
        }
        Equip equip = EquipDataPool.getByName(roleEquip.getName());
        if (equip == null) {
            log.error("找不到装备配置=[{}]", roleEquip.getName());
            return ERROR_RESOURCES;
        }
        Attribute attribute = attrService.getAttrByName(attrName.trim());
        String content = checkResource(role, roleEquip, opType, attribute.getAttrId());
        if (content != null) {
            return content;
        }

        return doUpgrade(role, roleEquip, attribute, opType, equip);
    }

    @Override
    public String checkResource(Object... objects) {
        Role role = (Role) objects[0];
        if (role.getLevel() < 110) {
            return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, "等级");
        }
        RoleEquip roleEquip = (RoleEquip) objects[1];
        String opType = (String) objects[2];
        short attrId = (short) objects[3];
        if (roleEquip.queryTransformTime() > Math.toIntExact(System.currentTimeMillis() / 1000)) {
            return MessageFormat.format(TRANSFORM_TIME, roleEquip.getName());
        }
        int stoneNum = equipService.getCount(STONE, true, role);
        if (stoneNum < 2) {
            return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, STONE);
        }
        int transformCount = roleEquip.queryTransformCount();
        if (transformCount >= 10) {
            return MessageFormat.format(MAX_TRANSFORM, roleEquip.getName());
        }
        int costEssence = getEssence(transformCount);
        if (role.getJewelryEssence() < costEssence) {
            return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, "首饰精华");
        }
        RoleEquipField blueFields = roleEquip.getFields().get((short) 514);

        RoleEquipField pinkFields = roleEquip.getFields().get((short) 770);
        AtomicBoolean exist = new AtomicBoolean(false);
        if (opType.equals("prop")) {
            blueFields.getField().keySet().forEach(attribute -> {
                if (attribute == attrId) {
                    exist.set(true);
                }
            });
            if (!exist.get()) {
                return FAIL_MESSAGE;
            }
        } else {
            pinkFields.getField().keySet().forEach(attribute -> {
                if (attribute == attrId) {
                    exist.set(true);
                }
            });
            if (!exist.get()) {
                return FAIL_MESSAGE;
            }
        }


        return null;
    }

    /**
     * 根据转换次数取扣除的精华
     */
    private int getEssence(int transformConut) {
        return COST_ESSENCE.get(transformConut);
    }

    @Override
    boolean isRightPosition(byte equipPos) {
        return equipPos == NECKLACE || equipPos == BALDRIC || equipPos == LEFT_WRIST;
    }

    @Override
    public int needCash(short level, int pos) {
        return 0;
    }

    @Override
    public String getUpdateTypeStr() {
        return "transform_jewelry";
    }
}
